import {zhooks} from 'ym-design';
const {useRequest } = zhooks;

function getUsername(userId?: string): Promise<string> {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      // const name = '@name' + Math.random();
      // resolve(name);
      console.log('--getUsername--触发--');
      if (Math.random() > 0.5) {
        resolve('@name' + Math.random());
      } else {
        reject(new Error('Failed to get username'));
      }
    }, 3000);
  });
}

function HookUseRequestBasic() {
  const { data, loading, error, run, params, cancel, refresh, mutate } = useRequest(getUsername, {
    onBefore: () => {
      console.log('onBefore');
    },
    onSuccess: (data:any, params:any) => {
      console.log('--onSuccess--data--params--', data, params);
    },
    onError: (error:any) => {
      console.log('--onError--', error);
    },
    onFinally: (params:any, data:any, error:any) => {
      console.log('--onFinally--params--data--error--:', params, data, error);
    },
  });
  // if (loading) {
  //   return <div>loading...</div>;
  // }

  const handleMutate = () => {
    mutate((prevData: any) => {
      return prevData + '改';
    });
  };

  return (
    <div>
      <div>
        <h3>useRequest(service),service必须return Promise</h3>
        <h3>useRequest,整个生命周期都不能对data做处理,return 的data都是原始数据。</h3>
      </div>
      <div>
        <p>
          params:
          {params?.map((p:any, pIndex:any) => (
            <span key={pIndex}>{p}</span>
          ))}
        </p>
        <p>data:{data}</p>
      </div>

      {error && <div style={{ color: 'red' }}>{error.message}</div>}
      <button onClick={() => run('123')} disabled={loading}>
        run1(123)---基础用法
      </button>
      <button onClick={() => run('456')} disabled={loading}>
        run1(456)
      </button>
      <button onClick={cancel}>cancel</button>
      <button onClick={refresh}>refresh</button>
      <button onClick={handleMutate}>立即变更数据</button>
    </div>
  );
}

export default HookUseRequestBasic;